package SortAlgorithm;

/**
 * @author gao
 * @date 2025/11/7 19:31
 */

public class HeapSort implements Sort {

    @Override
    public void sort(int[] nums) {
        createHeap(nums);
        int end = nums.length - 1;
        while (end > 0) {
            swap(nums, 0, end);
            shiftDown(nums, 0, end);
            end--;
        }
    }

    private void shiftDown(int[] nums, int parent, int length) {
        int child = 2 * parent + 1;
        while (child < length) {
            if (child + 1 < length && nums[child] < nums[child + 1]) {
                child++;
            }
            if (nums[child] > nums[parent]) {
                swap(nums,parent,child);
                parent = child;
                child = 2 * parent + 1;
            } else {
                break;
            }
        }
    }

    private void swap(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }

    private void createHeap(int[] nums) {
        for (int parent = (nums.length - 1 - 1) / 2; parent >= 0; parent--) {
            shiftDown(nums, parent, nums.length);
        }
    }
}